#include "ao_sink.h"

#include <ao/ao.h>

using namespace pita;

struct AOSink::Shared
{
		Shared() { ao_initialize(); }
		~Shared() { ao_shutdown(); }
};

AOSink::Shared* AOSink::shared_ = NULL;
unsigned int AOSink::share_count_ = 0;

AOSink::AOSink() :
	driver_ (-1),
	device_ (NULL)
{
	if (!shared_)
	{
		assert(share_count_ == 0);
		shared_ = new Shared;
	}
	++share_count_;

	driver_ = ao_default_driver_id();

	ao_sample_format format;
	format.bits = 16;
	format.channels = 2;
	format.rate = 44100;
	format.byte_format = AO_FMT_LITTLE;

	device_ = ao_open_live(driver_, &format, NULL /* no options */);
}

AOSink::~AOSink()
{
	ao_close(device_);

	--share_count_;
	if (0 == share_count_)
	{
		delete shared_;
		shared_ = NULL;
	}
}

void AOSink::play(const DataChunk& chunk)
{
	if (device_) 
		ao_play(device_, const_cast<char*>(&chunk[0]), chunk.size());
}
